import "./index.scss"
import "./ai-content.scss"
import { useState } from "react";
import { Input, Segmented, Row, Col } from 'antd'
import { LoadingOutlined } from '@ant-design/icons';
import api from "../../api";
import MarkdownIt from "markdown-it"
const hljs = require('highlight.js');

const { Search } = Input;
const avatar = require("@/assets/images/avatar2.jpeg");

const md = new MarkdownIt({
  highlight: function (str, lang) {
    if (lang && hljs.getLanguage(lang)) {
      try {
        return hljs.highlight(str, { language: lang }).value;
      } catch (__) { }
    }
    return ''; // 使用额外的默认转义
  }
});
const AIChat = () => {
  const [messages, setMessages] = useState([
    // {
    //   role: "assistant",
    //   content: "你好，我是AI小助手，请问有什么可以帮到您？",
    //   type: "loading"
    // },
    // {
    //   role: "user",
    //   content: "我想了解一下AI的发展历史"
    // }
  ])
  const [type, setType] = useState("deepseek")
  const [ques, setQues] = useState("")
  const [loading, setLoading] = useState(false)
  const onSearch = async () => {
    if (!ques) return
    setLoading(true)
    // console.log(type)
    const question = ques;
    const userMsg = {
      role: "user",
      content: question
    }
    const assistantMsg = {
      role: "assistant",
      content: "",
      type: "loading"
    }
    setMessages((msgs) => [...msgs, userMsg, assistantMsg])
    setQues("")

    // 去除 reasoning_content
    const tmpMessages = messages.map(item => {
      return {
        role: item.role,
        content: item.content
      }
    })
    // 调用接口
    const data = {
      messages: [...tmpMessages, userMsg]
    }
    // api.chat.chat(data).then(res => {
    //   const assistantMsg = res.data
    //   // 添加markdown解析
    //   assistantMsg.HTMLContent = md.render(assistantMsg.content);

    //   setMessages((msg) => { 
    //     const preMsg = msg.slice(0, msg.length - 1)
    //     console.log(preMsg)
    //     return [...preMsg, assistantMsg]
    //   })
    //   setLoading(false)
    // })

    const response = await fetch('/dev-api/api/chat', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': localStorage.getItem('token')
      },
      body: JSON.stringify(data)
    });
    const reader = response.body.getReader();
    const decoder = new TextDecoder();
    
    let _reason = ""; // 用于记录每次读取的原因
    let _content = ""; // 用于记录每次读取的数据
    while(true) {
      const { done, value } = await reader.read();
      if (done) {
        break;
      }
    
      setLoading(false); // 在接收到数据后设置加载状态为 false
      const chunk = decoder.decode(value);
      chunk.split('\n\n').forEach(event => {
        if (event.trim() === 'data: [DONE]') return;
        
        if (event.startsWith('data: ')) {
          const json = JSON.parse(event.replace('data: ', ''));
          _content += json.content;
          _reason += json.reason;
          setMessages(prev => {
            const newMessages = [...prev];
            const lastMsg = newMessages[newMessages.length - 1];
            lastMsg.content = _content;
            lastMsg.reason = _reason;
            lastMsg.HTMLContent = md.render(_content);
            lastMsg.type = "text";
            return newMessages;
          });
        }
      });
    }

  }
  return (
    <div className="ai-chat">
      {/* 聊天对话框 */}
      <div className="chat-box">
        {
          messages.map((item, index) => {
            return (
              item.role == "assistant" ?
                <div key={index} className="ai">
                  <div className="ai-avatar">AI</div>
                  {/* <div className="ai-content">{ item.type === "loading" ? <LoadingOutlined /> : item.HTMLContent }</div> */}
                  {
                    item.type === "loading" ? 
                      <div className="ai-content">
                        <LoadingOutlined />
                      </div>
                      :
                      <div>
                        <div className="ai-reason">{ item.reason }</div>
                        <div className="ai-content" dangerouslySetInnerHTML={{ __html: item.HTMLContent }}></div>
                      </div>
                  }
                </div>
                :
                <div key={index} className="user">
                  <div className="user-content">{item.content}</div>
                  <img className="user-avatar" src={avatar} />
                </div>
            )
          })
        }
      </div>
      <div className="input-box">
        <Row gutter={[0, 6]}>
          <Col span={24}>
            <Search
              placeholder="你好，我是小助手，请问有什么可以帮到您？"
              allowClear
              enterButton="询问"
              size="large"
              value={ques}
              loading={loading}
              onSearch={onSearch}
              onChange={e => setQues(e.target.value)}
            />
        </Col>
        <Row>
          <Col span={24}>
            <Segmented
              val={type}
              options={['deepseek', '数据库']}
              onChange={val => setType(val)}
            />
          </Col>
        </Row>
        </Row>
      </div>
    </div>
  )
}

export default AIChat;
